from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from user import models
from user.models import Role,UrlInfo,User
from utils.MyBaseView import create_token


class UserAppSer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()
    phone = serializers.CharField()

    token = serializers.CharField(read_only=True)


    def create(self, data):
        user_obj = models.User.objects.create(**data)
        password = make_password(data.get('password'))
        user_obj.password = password
        user_obj.save()
        # 补充生成记录登录状态的token
        token = create_token(user_obj)
        user_obj.token = token
        return user_obj


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model=User
        fields='__all__'



class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model=Role
        fields='__all__'


class UrlSerializer(serializers.ModelSerializer):
    class Meta:
        model=UrlInfo
        fields='__all__'